import { type PluginOption } from 'vite'
import { parseAllVueCompInfo, watchVueFileChange } from './vueDocGenerator.js'
import { FSWatcher } from 'chokidar'

export const virtualModuleId = 'virtual:vue-comp-doc'

export function viteVueDocDataPlugin(glob: string | string[]) {
  let cache: Record<string, string> = Object.create({})
  let watcher: FSWatcher
  const resolvedVirtualModuleId = `\0${virtualModuleId}`
  console.log('虚拟组件创建, glob表达式为: ', glob)
  return {
    name: 'vite-plugin-vue-comp-doc',
    enforce: 'pre',
    async configResolved(resolvedConfig) {},
    closeBundle() {
      console.log('closeBundle生命周期方法')
      if (watcher) watcher.close()
    },
    async configureServer(server) {
      console.log('configureServer生命周期方法')
      if (watcher) watcher.close()
      watcher = watchVueFileChange(glob, server)
      cache = await parseAllVueCompInfo(glob)
    },
    // 将真实的虚拟模块id，转换为内部的虚拟模块id
    resolveId(id) {
      if (id === virtualModuleId) {
        return resolvedVirtualModuleId
      }
    },
    async load(id) {
      // 检查请求的ID是否是我们想要提供虚拟数据的路径
      if (id === resolvedVirtualModuleId) {
        // 在这里你可以从任何地方获取数据，比如读取本地JSON文件

        const jsonStr = JSON.stringify(cache)
        // 将数据转换为 JavaScript 字符串
        const code = `export default ${jsonStr}`

        // 返回虚拟模块的结果
        return {
          code,
          map: null, // 如果需要的话，可以返回 sourcemap
        }
      }
      return null // 对非虚拟数据请求不做处理
    },
  } as PluginOption
}
